interface CalculationResult {
    y?: number;
    off?: number;
    crossBorderDelivery: number;
    local: number;
    pay: number;
    platformCommission: number;
    sfpFee: number;
    talentCommission: number;
    transactionFee: number;
    vat: number;
    bonusCashbackFee: number;
    actualProfit: number;
}

export function calculateY(
    profitValue: number,
    profitType: 'fixed' | 'cost' | 'price',
    cost: number,
    _coupon: number,
    off: number,
    weight: number,
    withdrawalFeeRate: number = 0.01,
    platformCommissionRate: number = 0.054,
    sfpFeeRate: number = 0,
    talentCommissionRate: number = 0.01,
    transactionFeeRate: number = 0.0378,
    vatRate: number = 0.1,
    bonusCashbackRate: number = 0.0435,
    logisticsCostPer10g: number = 0.15,
    exchangeRate: number = 1.6412,
    buyerShippingFee: number = 10
): CalculationResult {
    // 计算跨境物流成本
    const crossBorderDelivery = Math.ceil(weight / 10) * logisticsCostPer10g * exchangeRate;

    // 计算固定费用（买家支付的运费 * 汇率）
    const FIXED_FEE = buyerShippingFee * exchangeRate;
    const LOCAL_MARKUP = 1 + vatRate;
    const coupon = exchangeRate * _coupon;

    // 定义函数来计算本地展示价和买家实付
    function calculateLocalAndPay(y: number) {
        const deliver = crossBorderDelivery;
        const local = (y + deliver) * LOCAL_MARKUP;
        const pay = local * off - coupon + FIXED_FEE;
        return { local, pay };
    }

    // 定义目标函数，用于牛顿迭代法
    function targetFunction(y: number) {
        const { local, pay } = calculateLocalAndPay(y);

        // 根据利润类型计算实际利润
        let actualProfit: number;
        switch (profitType) {
            case 'fixed':
                actualProfit = profitValue;
                break;
            case 'cost':
                actualProfit = cost * (profitValue / 100);
                break;
            case 'price':
                const sellingPrice = local * off - coupon;
                actualProfit = sellingPrice * (profitValue / 100);
                break;
            default:
                throw new Error('未知的利润类型: ' + profitType);
        }

        // 平台佣金
        const platformCommission = (local * off - coupon) * platformCommissionRate;
        // sfp服务费
        const sfpFee = (local * off - coupon) * sfpFeeRate;
        // 达人佣金
        const talentCommission = (local * off - coupon) * talentCommissionRate;
        // 交易手续费
        const transactionFee = pay * transactionFeeRate;
        // 奖金返现服务费
        const bonusCashbackFee = pay * bonusCashbackRate;
        // 增值税
        const vat = (pay - FIXED_FEE) / LOCAL_MARKUP * vatRate;
        // 实际运费
        const actualDelivery = crossBorderDelivery;

        const numerator = (actualProfit + cost) / (1 - withdrawalFeeRate) +
            platformCommission +
            sfpFee +
            talentCommission +
            transactionFee +
            vat +
            actualDelivery +
            bonusCashbackFee +
            coupon;

        const denominator = off;

        return LOCAL_MARKUP * y - (numerator / denominator - crossBorderDelivery * LOCAL_MARKUP);
    }

    // 使用牛顿迭代法求解y
    let y = 10; // 初始猜测值
    const tolerance = 0.0001; // 容差
    const maxIterations = 100; // 最大迭代次数
    let iteration = 0;
    let error = 1;

    while (iteration < maxIterations && error > tolerance) {
        const f = targetFunction(y);

        // 计算导数（数值近似）
        const h = 0.0001;
        const fPlusH = targetFunction(y + h);
        const derivative = (fPlusH - f) / h;

        // 避免除以零
        if (Math.abs(derivative) < 1e-10) {
            break;
        }

        const yNew = y - f / derivative;
        error = Math.abs(yNew - y);
        y = yNew;
        iteration++;
    }

    // 计算详细结果
    const { local, pay } = calculateLocalAndPay(y);
    // 根据利润类型计算实际利润
    let actualProfit: number;
    switch (profitType) {
        case 'fixed':
            actualProfit = profitValue;
            break;
        case 'cost':
            actualProfit = cost * (profitValue / 100);
            break;
        case 'price':
            const sellingPrice = local * off - coupon;
            actualProfit = sellingPrice * (profitValue / 100);
            break;
        default:
            actualProfit = 0;
    }

    // 计算各项费用
    const platformCommission = (local * off - coupon) * platformCommissionRate;
    const sfpFee = (local * off - coupon) * sfpFeeRate;
    const talentCommission = (local * off - coupon) * talentCommissionRate;
    const transactionFee = pay * transactionFeeRate;
    const bonusCashbackFee = pay * bonusCashbackRate;
    const vat = (pay - FIXED_FEE) / LOCAL_MARKUP * vatRate;

    return {
        y,
        crossBorderDelivery,
        local,
        pay,
        platformCommission,
        sfpFee,
        talentCommission,
        transactionFee,
        vat,
        bonusCashbackFee,
        actualProfit
    };
}

export function calculateOff(
    y: number,
    profitValue: number,
    profitType: 'fixed' | 'cost' | 'price',
    cost: number,
    _coupon: number,
    weight: number,
    withdrawalFeeRate: number = 0.01,
    platformCommissionRate: number = 0.054,
    sfpFeeRate: number = 0,
    talentCommissionRate: number = 0.01,
    transactionFeeRate: number = 0.0378,
    vatRate: number = 0.1,
    bonusCashbackRate: number = 0.0435,
    logisticsCostPer10g: number = 0.15,
    exchangeRate: number = 1.6412,
    buyerShippingFee: number = 10
): CalculationResult {
    // 计算跨境物流成本
    const crossBorderDelivery = Math.ceil(weight / 10) * logisticsCostPer10g * exchangeRate;

    // 计算固定费用（买家支付的运费 * 汇率）
    const FIXED_FEE = buyerShippingFee * exchangeRate;
    const LOCAL_MARKUP = 1 + vatRate;
    const coupon = exchangeRate * _coupon;

    // 定义目标函数，用于牛顿迭代法
    function targetFunction(off: number) {
        // 计算本地展示价和买家实付
        const deliver = crossBorderDelivery;
        const local = (y + deliver) * LOCAL_MARKUP;
        const sellingPrice = local * off - coupon;
        const pay = sellingPrice + FIXED_FEE;

        // 根据利润类型计算实际利润
        let actualProfit: number;
        switch (profitType) {
            case 'fixed':
                actualProfit = profitValue;
                break;
            case 'cost':
                actualProfit = cost * (profitValue / 100);
                break;
            case 'price':
                actualProfit = sellingPrice * (profitValue / 100);
                break;
            default:
                throw new Error('未知的利润类型: ' + profitType);
        }

        // 平台佣金
        const platformCommission = sellingPrice * platformCommissionRate;
        // sfp服务费
        const sfpFee = sellingPrice * sfpFeeRate;
        // 达人佣金
        const talentCommission = sellingPrice * talentCommissionRate;
        // 交易手续费
        const transactionFee = pay * transactionFeeRate;
        // 奖金返现服务费
        const bonusCashbackFee = pay * bonusCashbackRate;
        // 增值税
        const vat = (pay - FIXED_FEE) / LOCAL_MARKUP * vatRate;
        // 实际运费
        const actualDelivery = crossBorderDelivery;

        // 计算方程两边
        const leftSide = LOCAL_MARKUP * y;
        const numerator = (actualProfit + cost) / (1 - withdrawalFeeRate) +
            platformCommission +
            sfpFee +
            talentCommission +
            transactionFee +
            vat +
            actualDelivery +
            bonusCashbackFee +
            coupon;
        const rightSide = numerator / off - crossBorderDelivery * LOCAL_MARKUP;

        return leftSide - rightSide;
    }

    // 使用牛顿迭代法求解off
    let off = 0.5; // 初始猜测值（50%折扣）
    const tolerance = 0.0001; // 容差
    const maxIterations = 100; // 最大迭代次数
    let iteration = 0;
    let error = 1;

    while (iteration < maxIterations && error > tolerance) {
        const f = targetFunction(off);

        // 计算导数（数值近似）
        const h = 0.0001;
        const fPlusH = targetFunction(off + h);
        const derivative = (fPlusH - f) / h;

        // 避免除以零
        if (Math.abs(derivative) < 1e-10) {
            break;
        }

        let offNew = off - f / derivative;
        // 确保折扣率在合理范围内（0.01到1之间）
        offNew = Math.max(0.01, Math.min(1, offNew));

        error = Math.abs(offNew - off);
        off = offNew;
        iteration++;
    }

    // 计算详细结果
    const deliver = crossBorderDelivery;
    const local = (y + deliver) * LOCAL_MARKUP;
    const sellingPrice = local * off - coupon;
    const pay = sellingPrice + FIXED_FEE;

    // 根据利润类型计算实际利润
    let actualProfit: number;
    switch (profitType) {
        case 'fixed':
            actualProfit = profitValue;
            break;
        case 'cost':
            actualProfit = cost * (profitValue / 100);
            break;
        case 'price':
            actualProfit = sellingPrice * (profitValue / 100);
            break;
        default:
            actualProfit = 0;
    }

    // 计算各项费用
    const platformCommission = sellingPrice * platformCommissionRate;
    const sfpFee = sellingPrice * sfpFeeRate;
    const talentCommission = sellingPrice * talentCommissionRate;
    const transactionFee = pay * transactionFeeRate;
    const bonusCashbackFee = pay * bonusCashbackRate;
    const vat = (pay - FIXED_FEE) / LOCAL_MARKUP * vatRate;

    return {
        off,
        crossBorderDelivery,
        local,
        pay,
        platformCommission,
        sfpFee,
        talentCommission,
        transactionFee,
        vat,
        bonusCashbackFee,
        actualProfit
    };
} 